import 'package:flutter/material.dart';
import 'package:flutter_redux/flutter_redux.dart';
import 'package:list_test/store/redux_core.dart';
import 'package:list_test/store/actions.dart';
import 'package:list_test/weight.dart';
import 'package:list_test/weight_item.dart';
import 'package:list_test/dialog.dart';

class HistoryPageViewModel {
  final List entries;
  final Function(Weight) editEntryCallback;
  final Function(Weight) addEntryCallback;

  HistoryPageViewModel({
    this.entries,
    this.editEntryCallback,
    this.addEntryCallback
  });
}

class HistoryPage extends StatelessWidget {
  HistoryPage({ Key key, this.title }): super(key: key);
  final String title;

  @override
  Widget build(BuildContext context) {
    return new StoreConnector<ReduxState, HistoryPageViewModel>(
      converter: (store) {
        return new HistoryPageViewModel(
          entries: store.state.entries,
          addEntryCallback: ((entry) =>
              store.dispatch(new AddEntryAction(entry))),
          editEntryCallback: ((entry) =>
              store.dispatch(new EditEntryAction(entry))),
        );
      },
      builder: (context, viewModel) {
        return new ListView.builder(
          shrinkWrap: true,
          itemCount: viewModel.entries.length,
          itemBuilder: (buildContext, index) {
            double diff = index == viewModel.entries.length - 1
              ? 0.0
              : viewModel.entries[index].weight -
                viewModel.entries[index + 1].weight;
            return new InkWell(
              onTap: () => _openEditDialog(viewModel.entries[index], context, viewModel.editEntryCallback),
              child: new WeightItem(viewModel.entries[index], diff),
            );
          }
        );
      },
    ); 
  }

  Future _openEditDialog(Weight weight, BuildContext context, Function onSubmittedCallback) async{
    Weight result = await Navigator.of(context).push(new MaterialPageRoute<Weight>(
      builder: (BuildContext build) {
        return new AddEntryDialog.edit(weight);
      },
      fullscreenDialog: true,
    ));
    if (result != null) {
      result.key = weight.key;
      onSubmittedCallback(result);
    }
  }
}